<template>
  <div id="tmanager">
    <div class="search"></div>
    <div class="t_header">
      <el-button type="primary" @click="addTemplate">新增模板</el-button>
      <el-dialog
        title="新增模板"
        width="1000px"
        v-if="addTemplateFormDialog"
        :visible.sync="addTemplateFormDialog"
        destroy-on-close
      >
        <el-form
          :model="addTemplateForm"
          :rules="addTemplateRules"
          ref="addTemplateForm"
        >
          <el-form-item
            label="模板名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input
              v-model="addTemplateForm.name"
              autocomplete="off"
              placeholder="同一个项目模板名称不能重复"
              style="width: 500px"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="项目"
            :label-width="formLabelWidth"
            prop="pjcode"
          >
            <el-select
              v-model="addTemplateForm.pjcode"
              placeholder="请选择模板所属系统"
              filterable
            >
              <el-option
                v-for="pj in pjList"
                :key="pj.value"
                :label="pj.label"
                :value="pj.value"
                :filterable="true"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="默认环境"
            :label-width="formLabelWidth"
            prop="env"
          >
            <el-select
              v-model="addTemplateForm.env"
              placeholder="请选择默认环境"
              filterable
            >
              <el-option label="测试环境" value="QA"></el-option>
              <el-option label="生产环境" value="PROD"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="模板格式"
            :label-width="formLabelWidth"
            prop="format"
          >
            <el-select
              v-model="addTemplateForm.format"
              @change="changeMode"
              placeholder="请选择模板格式"
              filterable
            >
              <el-option
                v-for="mode in modes"
                :key="mode.value"
                :label="mode.label"
                :value="mode.value"
              >
              </el-option>
            </el-select>
            <span class="tips">暂时只支持YAML格式配置</span>
          </el-form-item>
          <el-form-item label="脚本内容" :label-width="formLabelWidth">
            <div class="mirrorbox">
              <textarea ref="textarea" :value="code"></textarea>
            </div>
          </el-form-item>
          <el-form-item
            label="模板说明"
            :label-width="formLabelWidth"
            prop="mark"
          >
            <el-input
              type="textarea"
              v-model="addTemplateForm.mark"
              style="box-shadow: 5px 5px 5px #888888; font-size: 18px"
              :rows="5"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addTemplateFormDialog = false">取 消</el-button>
            <el-button type="primary" @click="onSubmit()">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <el-table
      :data="tempList"
      border
      style="width: 100%"
      :header-cell-style="{ background: '#EEF1F6', color: '#909399' }"
    >
      <el-table-column
        label="序号"
        type="index"
        :index="table_index"
        align="center"
        width="80"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="模板名称"
        width="250"
      ></el-table-column>
      <el-table-column prop="pjname" label="项目" width="120">
      </el-table-column>
      <el-table-column
        prop="env"
        label="模板默认环境"
        :formatter="envCover"
        align="center"
        width="120"
      >
      </el-table-column>
      <el-table-column prop="user" label="创建人" align="center" width="100">
      </el-table-column>
      <el-table-column
        prop="createtime"
        label="创建时间"
        align="center"
        width="220"
      >
      </el-table-column>
      <el-table-column prop="yamldata" label="原始数据" width="300">
        <template slot-scope="scope">
          <el-popover
            placement="top-start"
            width="600"
            trigger="hover"
            :disabled="scope.row.yamldata.length <= 75"
          >
            <div>{{ scope.row.yamldata }}</div>
            <span slot="reference" v-if="scope.row.yamldata.length <= 75">{{
              scope.row.yamldata
            }}</span>
            <span slot="reference" v-if="scope.row.yamldata.length > 75">{{
              scope.row.yamldata.substr(0, 75) + "..."
            }}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="jsondata" label="转换数据" width="300">
        <template slot-scope="scope">
          <el-popover
            placement="top-start"
            width="300"
            trigger="hover"
            :disabled="scope.row.jsondata.length <= 75"
          >
            <div>{{ scope.row.jsondata }}</div>
            <span slot="reference" v-if="scope.row.jsondata.length <= 75">{{
              scope.row.jsondata
            }}</span>
            <span slot="reference" v-if="scope.row.jsondata.length > 75">{{
              scope.row.jsondata.substr(0, 75) + "..."
            }}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="mark" label="模板说明" width="200">
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="360">
        <template #default="scope">
          <el-button @click="tedit = true" type="primary" size="small">
            详情
          </el-button>
          <el-button @click="tdetail = true" type="primary" size="small">
            编辑
          </el-button>
          <el-button @click="openExeDialog(scope)" type="primary" size="small">
            执行
          </el-button>
          <el-button @click="thistery = true" type="primary" size="small">
            执行历史
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-drawer
      title="运行脚本"
      v-if="openflag"
      :visible.sync="openflag"
      :direction="direction"
      :before-close="handleClose"
      size="40%"
      destroy-on-close
      :closed="info()"
    >
      <exe-temp :rowdata="rowdata"></exe-temp>
    </el-drawer>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 50, 100, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
// import { defineComponent, ref } from "vue";
import ExeTemp from "./common/exescript";
import common from "@/api/common";
import axios from "axios";
import _CodeMirror from "codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/idea.css";
import "codemirror/mode/yaml/yaml.js";
import "codemirror/mode/sql/sql.js";
import "codemirror/mode/python/python.js";
import "codemirror/mode/javascript/javascript.js";
import "codemirror/addon/hint/javascript-hint";
import "codemirror/addon/hint/sql-hint";
import "codemirror/addon/hint/anyword-hint";

const CodeMirror = window.CodeMirror || _CodeMirror;

export default {
  name: "tmplist",
  components: {
    ExeTemp,
  },
  props: {
    value: String,
    language: {
      type: String,
      default: null,
    },
  },

  data() {
    return {
      rowdata: Object,
      centerDialogVisible: false,
      tempvar: "",
      currentPage: 1,
      pjList: new Array(),
      pageSize: 10,
      total: 0,
      code: "",
      height: "10px",
      tedit: false,
      tdetail: false,
      openflag: false,
      thistery: false,
      addTemplateFormDialog: false,
      direction: "rtl",
      radio1: "1",
      textarea: "",
      addTemplateForm: {
        name: "",
        pjcode: "",
        env: "QA",
        format: "",
        mark: "",
      },
      addTemplateRules: {
        name: [
          { required: true, message: "请输入模板名称", trigger: "blur" },
          {
            min: 2,
            max: 30,
            message: "长度在 2 到 30 个字符",
            trigger: "blur",
          },
        ],
        pjcode: [{ required: true, message: "请选择项目", trigger: "change" }],
        env: [{ required: true, message: "请选择项目环境", trigger: "change" }],
        format: [
          {
            required: true,
            message: "请选择模板格式，暂时只支持yaml",
            trigger: "change",
          },
        ],
        mark: [
          {
            required: false,
            message: "请输入按要求输入模板说明",
            trigger: "blur",
          },
          {
            min: 0,
            max: 200,
            message: "长度在 1 到 200 个字符",
            trigger: "blur",
          },
        ],
      },
      formSearch: {
        name: "",
        pjname: "",
      },
      formLabelWidth: "120px",
      mode: "请选择脚本格式",
      coder: null,
      options: {
        tabSize: 2,
        theme: "idea",
        lineNumbers: true,
        line: true,
        height: 20,
        length: 0,
        foldGutter: true,
        lineWrapping: true,
        gutters: [
          "CodeMirror-linenumbers",
          "CodeMirror-foldgutter",
          "CodeMirror-lint-markers",
        ],
      },
      modes: [
        {
          value: "x-python",
          label: "Python",
        },
        {
          value: "x-sql",
          label: "SQL",
        },
        {
          value: "x-yaml",
          label: "Yaml",
        },
        {
          value: "javascript",
          label: "Json",
        },
      ],
      tempList: new Array(),
    };
  },
  created: function () {
    this.getTempList();
  },

  methods: {
    info() {
      console.log(this.rowdata);
    },
    openExeDialog(rowid) {
      this.openflag = true;
      this.rowdata = rowid.row;
    },
    fmethod() {
      return this.rowid;
    },
    table_index(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getTempList(this.pageSize, this.currentPage);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTempList(this.pageSize, this.currentPage);
    },
    success(msg) {
      this.$notify({
        title: "成功",
        message: msg,
        type: "success",
      });
    },
    warningInfo(msg) {
      this.$notify({
        title: "警告",
        message: msg,
        type: "warning",
      });
    },
    errorInfo(msg) {
      this.$notify.error({
        title: "错误",
        message: msg,
      });
    },
    onSubmit() {
      this.$refs["addTemplateForm"].validate((valid) => {
        if (valid) {
          console.log("校验通过");
        } else {
          return false;
        }
      });

      let formData = new FormData();
      for (var key in this.addTemplateForm) {
        formData.append(key, this.addTemplateForm[key]);
      }
      formData.append("script", this.code);
      axios({
        method: "post",
        url: "/sqltemplate/createtemplate",
        Headers: {
          "Content-Type": "multipart/form-data",
        },
        withCredentials: true,
        data: formData,
      }).then((res) => {
        if (common.checkIsLogin(res)) {
          if (res.data["sucess"] == 1) {
            this.success("模板新增成功");
            this.addTemplateFormDialog = false;
            this.getTempList();
            Object.assign(this.$data, this.$options.data());
          } else {
            this.warningInfo(res.data["msg"]);
          }
        } else {
          this.errorInfo(res.data.msg);
        }
      });
    },
    getTempList(pageSize = this.pageSize, currentPage = this.currentPage) {
      axios({
        method: "GET",
        url:
          "/sqltemplate/createtemplate?pagesize=" +
          pageSize +
          "&currentpage=" +
          currentPage,
        withCredentials: true,
      }).then((res) => {
        if (common.checkIsLogin(res)) {
          this.tempList = res.data.data;
          this.total = res.data.total;
        } else {
          this.errorInfo(res.data.msg);
        }
      });
    },
    handleClick(row) {
      console.log(row);
    },
    handleClose(done) {
      this.openflag = false;
    },
    open4() {
      this.$notify.error({
        title: "错误",
        message: "请检查你的模板内容是否正确",
      });
    },
    _initialize() {
      this.coder = CodeMirror.fromTextArea(this.$refs.textarea, this.options);
      this.coder.setValue(this.value || this.code);
      this.coder.on("change", (coder) => {
        this.code = coder.getValue();
        if (this.$emit) {
          this.$emit("input", this.code);
        }
      });
      if (this.language) {
        let modeObj = this._getLanguage(this.language);
        if (modeObj) {
          this.mode = modeObj.label;
        }
      }
    },
    mounted() {
      this._initialize();
    },
    _getLanguage(language) {
      return this.modes.find((mode) => {
        let currentLanguage = language.toLowerCase();
        let currentLabel = mode.label.toLowerCase();
        let currentValue = mode.value.toLowerCase();
        return (
          currentLabel === currentLanguage || currentValue === currentLanguage
        );
      });
    },
    changeMode(val) {
      this.coder.setOption("mode", `text/${val}`);
      let label = this._getLanguage(val).label.toLowerCase();
      this.$emit("language-change", label);
    },
    addTemplate() {
      this.addTemplateFormDialog = true;
      this.$nextTick(function () {
        this._initialize();
      });
      this.getPorjectList();
    },
    envCover(row, colum) {
      return row.env == "QA" ? "测试环境" : "生产环境";
    },
    getPorjectList(pageSize = 10000, currentPage = this.currentPage) {
      axios({
        method: "GET",
        url:
          "/sqltemplate/projectinfo?pagesize=" +
          pageSize +
          "&currentpage=" +
          currentPage,
        withCredentials: true,
      }).then((res) => {
        if (common.checkIsLogin(res)) {
          if (res.data.code !== 1) {
            this.errorInfo("项目列表获取失败");
          } else {
            const tempList = new Array();
            const result = res.data.data;
            result.forEach((element) => {
              const tempObj = new Object();
              tempObj.label = element.pjname;
              tempObj.value = element.pjcode;
              tempList.push(tempObj);
            });
            this.pjList = tempList;
            // console.log(tempList);
          }
        } else {
          this.errorInfo(res.data.msg);
        }
      });
    },
  },
};
</script>

<style>
.t_header {
  margin-bottom: 10px;
}
.el-dialog__body {
  height: 55vh;
  overflow: auto;
}
.in-coder-panel {
  flex-grow: 1;
  display: flex;
  position: relative;
}

.CodeMirror {
  flex-grow: 1;
  z-index: 1;
  font-size: 20px;
  line-height: 150%;
}
.CodeMirror-code {
  line-height: 19px;
}

.code-mode-select {
  position: absolute;
  z-index: 2;
  right: 10px;
  top: 10px;
  max-width: 130px;
  line-height: 19px;
}
.tips {
  font-size: 12px;
  color: red;
  font-weight: 700;
}
.mirrorbox {
  border: 1px solid #888888;
  box-shadow: 5px 5px 5px #888888;
}
textarea {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  font-size: 20px;
}
.el-table__empty-block {
  min-height: 700px;
}
.el-table__body-wrapper {
  min-height: 700px;
}

.el-drawer__body {
  overflow: auto;
}

.el-popover {
  white-space: pre-line;
  background-color: #a3d1d1;
  font-weight: 700;
}
</style>